/*日历+下部列表
* 实现拖动列表，折叠展开日历
* 默认选中每月的1号（从_selectedDay入手，将需要选中的日期放在_selectedDay中）
* */

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frametrim/utility/sq_color.dart';
import 'package:frametrim/utility/timeUtil.dart';
import 'package:frametrim/views/calendar/shared/utils.dart';
import 'package:frametrim/views/calendar/table_calendar.dart';
// import 'package:table_calendar/table_calendar.dart';

import '../timeline.dart';
import 'customization/calendar_style.dart';
import 'customization/days_of_week_style.dart';

class MyStyleCalendarView2 extends StatefulWidget {
  late Widget listItem;
  late Function(DateTime) mFunction;

  MyStyleCalendarView2(this.listItem, this.mFunction);

  @override
  State<StatefulWidget> createState() => MyStyleCalendarState();
}

class MyStyleCalendarState extends State<MyStyleCalendarView2> {
  late DateTime _focusedDay;

  // late DateTime? _rangeStart=null;
  // late DateTime? _rangeEnd=null;
  DateTime? _selectedDay;
  late ValueNotifier<List> _selectedEvents;
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOff;

  /*刷新*/
  GlobalKey<MyStyleCalendarState> selectBtnKey = GlobalKey();

//手指移动的位置
  double _lastMoveY = 0.0;

  //手指按下的位置
  double _downY = 0.0;

  late ScrollController _controller = ScrollController();

  //是否滚动到顶部
  late bool isScrollTop = true;

  //是否滚动到底部
  late bool isScrollBottom = false;

  late ScrollPhysics physics = NeverScrollableScrollPhysics();

  @override
  void initState() {
    super.initState();
    /*默认选中的日期  2022-03-23 16:09:55.227473*/
    // _focusedDay=TimeUtil.getMonth();
    _focusedDay =
        TimeUtil.getMonthFirstDay(DateTime.now().year, DateTime.now().month);
    // print('_focusedDay==' + _focusedDay.toString());
    _selectedDay = _focusedDay;
    _selectedEvents = ValueNotifier(_getEventsForDay(_selectedDay!));
    // 初始化ScrollController
    _controller.addListener(() {
      // print('滚动位置=='+_controller.offset.toString());
      // print('滚动位置=='+_controller.position.toString());
      // print('滚动位置最底部=='+_controller.position.maxScrollExtent.toString());
      // print('滚动位置最顶部=='+_controller.position.minScrollExtent.toString());
      if (_controller.offset == _controller.position.maxScrollExtent) {
        isScrollBottom = true;
        isScrollTop = !isScrollBottom;
        print('滚动位置==最底部isScrollTop==' +
            isScrollTop.toString() +
            "isScrollBottom==" +
            isScrollBottom.toString());
      }
      if (_controller.offset == _controller.position.minScrollExtent) {
        isScrollTop = true;
        isScrollBottom = !isScrollTop;
        print('滚动位置==最顶部isScrollTop==' +
            isScrollTop.toString() +
            "isScrollBottom==" +
            isScrollBottom.toString());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
      decoration: BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.all(Radius.circular(5))),
      child: NestedScrollView(
        headerSliverBuilder: (context,b){
          return [
            SliverAppBar(
              backgroundColor: Colors.white,
              toolbarHeight: 92,
              //是否固定在顶部
              pinned: true,
              //是否随着滑动隐藏标题
              floating: true,
              //SliverAppBar展开的高度
              expandedHeight: 300,
                // toolbarHeight:
              flexibleSpace: Container(
                color: Colors.red,
                child: buildTableCalendar(),
              ),
              // flexibleSpace: buildTableCalendar(),
              leading: Container(),
            )
          ];
        },
        body: MediaQuery.removePadding(
          context: context,
          child: ListView(
            //禁止滚动
            physics: physics,
            children: <Widget>[widget.listItem],
            controller: _controller,
          ),
          removeTop: true,
        ),
      )
    );
  }

  /*
  * MediaQuery.removePadding(
              context: context,
              child: ListView(
                //禁止滚动
                physics: physics,
                children: <Widget>[widget.listItem],
                controller: _controller,
              ),
              removeTop: true,
            )*/

  /*日历*/
  Widget buildTableCalendar() {
    return TableCalendar(
      key: selectBtnKey,
      daysOfWeekHeight: 40,
      daysOfWeekStyle: DaysOfWeekStyle(
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      color: const Color.fromRGBO(213, 213, 213, 1),
                      width: 0.4)))),
      locale: 'zh_CN',
      firstDay: DateTime(2000, 1, 01),
      lastDay: DateTime(2022, 12, 31),
      headerVisible: false,
      // headerStyle: HeaderStyle(
      //     titleTextStyle: TextStyle(fontSize: 15)),
      focusedDay: _focusedDay,
      selectedDayPredicate: (day) => isSameDay(_selectedDay!, day),
      // rangeStartDay: _rangeStart,
      // rangeEndDay: _rangeEnd,
      calendarFormat: _calendarFormat,
      // rangeSelectionMode: _rangeSelectionMode,
      // eventLoader: _getEventsForDay,
      // startingDayOfWeek: StartingDayOfWeek.monday,
      /*选中样式*/
      calendarStyle: const CalendarStyle(
          //是否显示替他月的日期
          outsideDaysVisible: false,
          selectedDecoration: ShapeDecoration(
              color: Color.fromRGBO(0, 122, 255, 1),
              shape: CircleBorder(side: BorderSide.none)),
          todayDecoration:
              BoxDecoration(color: Color.fromRGBO(0, 122, 255, 0.5)),
          markersMaxCount: 1,
          markersAutoAligned: false),
      onDaySelected: onDaySelected,
      onRangeSelected: _onRangeSelected,
      /*设置折叠功能*/
      onFormatChanged: (format) {
        if (_calendarFormat != format /*&& format != CalendarFormat.twoWeeks*/) {
          /**
           *  _calendarFormat==CalendarFormat.week
           *  _calendarFormat==CalendarFormat.twoWeeks
           *  _calendarFormat==CalendarFormat.month
           */
          setState(() {
            _calendarFormat = format;
          });
          print('_calendarFormat==' + _calendarFormat.toString());
        }
      },
      /*切换月份时候，恢复默认选中，会有卡顿现象，待解决*/
      onPageChanged: (focusedDay) {
        _focusedDay = focusedDay;
        // sleep(Duration(seconds: 1));
        selectBtnKey.currentState!.onDaySelected(_focusedDay, _focusedDay);
        widget.mFunction(_focusedDay);
      },
    );
  }

  @override
  void dispose() {
    _selectedEvents.dispose();
    //为了避免内存泄露，需要调用_controller.dispose
    _controller.dispose();
    super.dispose();
  }

  List<DateTime> _daysInRange(DateTime first, DateTime last) {
    final dayCount = last.difference(first).inDays + 1;
    return List.generate(
      dayCount,
      (index) => DateTime.utc(first.year, first.month, first.day + index),
    );
  }

  List _getEventsForDay(DateTime day) {
    // Implementation example
    return [];
    // return kEvents[day] ?? [];
  }

  void onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay!, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        print('选中日期==' + _focusedDay.toString());
        // _rangeStart = null; // Important to clean those
        // _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      _selectedEvents.value = _getEventsForDay(selectedDay);
    }
  }

  void _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) {
    setState(() {
      _selectedDay = null;
      _focusedDay = focusedDay;
      // _rangeStart = start;
      // _rangeEnd = end;
      _rangeSelectionMode = RangeSelectionMode.toggledOn;
    });

    // `start` or `end` could be null
    if (start != null && end != null) {
      _selectedEvents.value = _getEventsForRange(start, end);
    } else if (start != null) {
      _selectedEvents.value = _getEventsForDay(start);
    } else if (end != null) {
      _selectedEvents.value = _getEventsForDay(end);
    }
  }

  List _getEventsForRange(DateTime start, DateTime end) {
    // Implementation example
    final days = _daysInRange(start, end);

    return [
      for (final d in days) ..._getEventsForDay(d),
    ];
  }
}
